<template>
	<view class="content-img">
		<eui-nav-bar title="写信" color="#000" rightIcon="" />
	</view>
	<view class="main-view">
		<scroll-view scroll-y :style="{width:scrollWidth,height:scrollHeight}">
			<eui-card leftPadding="28rpx" rightPadding="0px" vPadding="0px">
				<eui-card-input v-model="Info.c_title" title="标题" placeholder="请输入标题" type="text" alignType="right"
					hPadding="0" style="padding-right: 14px;" />
				<eui-card-input v-model="Info.c_receiver_name" title="收件人" placeholder="请选择或输入收件人" type="text"
					alignType="right" rightIconType="right" :isBlur="true" @confirm="onConfirm('c_receiver')"
					@iconClick="clickRight('reciver')" style="padding-right: 10px;" hPadding="0" />
				<eui-card-input v-model="Info.c_copy_receiver_name" title="抄送" placeholder="请选择或输入抄送" type="text"
					alignType="right" rightIconType="right" :isBlur="true" @confirm="onConfirm('c_copy_receiver')"
					@iconClick="clickRight('copyreciver')" style="padding-right: 10px;" hPadding="0" />
				<eui-card-input v-model="Info.c_content" title="内容" placeholder="请输入邮件内容" type="textarea"
					maxlength="500" style="padding-right: 14px;" hPadding="0" radius="10"/>
				<view class="margin-top-28 font-size-28 color-666">
					上传附件
				</view>
				<UploadOaFile v-model="fileList" :loadUrl="uploadUrl" @result="resultUrl" @delImg="delImg" loadCount='5'
					loadTotalCount="20" async="否" isFiles="是" imgSize="5"></UploadOaFile>
			</eui-card>
		</scroll-view>
		<view class="user-footer">
			<eui-button type="base2" @click="beforeSaveData('saveDraft')" title="保存草稿" singleTag="primary_主按钮" />
			<eui-button type="base" @click="beforeSaveData('send')" title="发送" singleTag="primary_主按钮" />
		</view>
	</view>
</template>

<script setup type="ts">
	import { onLoad,onReady } from '@dcloudio/uni-app';
	import { ref } from 'vue';
	import Enjoy from '@/common/enjoy';
	import Guid from '@/common/guid';
	import service from '@/common/service';
	import { useMainStore } from '@/store/modules/store';
	import { useLoginStore } from '@/store/modules/useLoginStore';
	import dateRangUtil from '@/common/dateRangUtil';
	import UploadOaFile from './UploadOaFile.vue';
	import useUpload from "@/hooks/useUpload";
	
	const { upload, remove, fetchFile } = useUpload({ prefix: 'mainApi' });
	const mainStore = useMainStore();
	const LoginStore = useLoginStore();
	const scrollWidth = ref(uni.getSystemInfoSync().windowWidth + 'px');
	const scrollHeight = ref((uni.getSystemInfoSync().windowHeight - uni.getSystemInfoSync().statusBarHeight-94) + 'px');
	
	const c_id = ref('');
	const Info = ref({
		c_title:'',
		c_receiver:'',
		c_receiver_name:'',
		c_copy_receiver:'',
		c_copy_receiver_name:'',
		c_content:'',
		attachment:[]
	});
	const readOnly = ref(false);
	const fileList = ref([]);
	const uploadUrl = ref(LoginStore.EnjoyMain.replace('/Enjoy/Service', ''));
	const idGuid = ref('');
	
	const onConfirm = item =>{
		if(item=='c_receiver'){
			if(Info.value.c_receiver_name){
				GetUserInfoList(item,Info.value.c_receiver_name);
			}else{
				Info.value.c_receiver='';
				Info.value.c_receiver_name='';
			}
		}else{
			if(Info.value.c_copy_receiver_name){
				GetUserInfoList(item,Info.value.c_copy_receiver_name);
			}else{
				Info.value.c_copy_receiver='';
				Info.value.c_copy_receiver_name='';
			}
		}
	}
	const clickRight = item =>{
		console.log('item',item);
		let parms = Enjoy.GetDialogParms();
		parms.CallBack=SelectionChanged;
		if(item=='reciver'){
			parms.IsMult="是";
			parms.SelectionType="人员选择";
			parms.SelectionAlias="选择收件人";
			parms.SelectedItems = Info.value.sStoreId;
		}else if(item=='copyreciver'){
			parms.IsMult="是";
			parms.SelectionType="人员选择";
			parms.SelectionAlias="选择抄送人";
			parms.SelectedItems = Info.value.c_adno;
		}
		Enjoy.OpenDialog(parms)
	}
	const SelectionChanged = (e) =>{
		console.log("SelectionChanged: " + JSON.stringify(e));
		if(e.SelectionType=='人员选择'&&e.SelectionAlias=='选择收件人'){
			Info.value.c_receiver=e.BackParms.Key;
			Info.value.c_receiver_name=e.BackParms.Value?e.BackParms.Value:'';
		}else{
			Info.value.c_copy_receiver=e.BackParms.Key;
			Info.value.c_copy_receiver_name=e.BackParms.Value?e.BackParms.Value:'';
		}
	}
	const GetUserInfoList = (k,v) =>{
		let list = [];
		if(v.indexOf(',')>=0){
			list = v.split(',');
		} else if(v.indexOf('，')>=0){
			list = v.split('，');
		} else {
			list = v.split(',');
		}
		let searchWhereList = [];
		let no = [];
		let name = [];
		service.enjoyShowLoading('正在加载...');
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40通讯录",
		        ObjectData: {
					IsNotPage: true,
					WhereList: null,
				},
		        MethodName: "GetUserInfoList",
		    },
		}
		service.request(request, (res) => {
		    if (res && res.data) {
		        if (!res.data.HasException) {
					const ReturnObject = res.data.ObjectData.ReturnObject;
					if(ReturnObject){
						for (let i = 0; i < ReturnObject.length; i++) {
							if(ReturnObject[i].c_name != 'Group'){
								for (let bb = 0; bb < list.length; bb++) {
									if(ReturnObject[i].c_userno==list[bb]||ReturnObject[i].c_name==list[bb]){
										no.push(ReturnObject[i].c_userno);
										name.push(ReturnObject[i].c_name);
									}
								}
							}
						}
						if(k=='c_receiver'){
							Info.value.c_receiver=no.toString();
							Info.value.c_receiver_name=name.toString();
						}else{
							Info.value.c_copy_receiver=no.toString();
							Info.value.c_copy_receiver_name=name.toString();
						}
					}
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message);
					if(k=='c_receiver'){
						Info.value.c_receiver='';
						Info.value.c_receiver_name='';
					}else{
						Info.value.c_copy_receiver='';
						Info.value.c_copy_receiver_name='';
					}
		        }
		    }
			service.enjoyHideLoading();
		}, () => {
			service.enjoyHideLoading();
		    console.log('失败')
		});
	}
	const beforeSaveData = type =>{
		if(!Info.value.c_title){
			uni.showToast({
				duration: 3500,
				icon: 'none',
				title: '标题不允许为空!'
			});
			return false;
		}
		if(!Info.value.c_content){
			uni.showToast({
				duration: 3500,
				icon: 'none',
				title: '内容不允许为空!'
			});
			return false;
		}
		if(!Info.value.c_receiver){
			uni.showModal({
				title: '提示',
				content: '当前收件人为空，将发送给所有用户，请确认?',
				success: function(res) {
					if (res.confirm) {
						beforeIsExistUser(type)
					}
				}
			})
		}else{
			uni.showModal({
				title: '提示',
				content: '是否保存当前设置，请确认?',
				success: function(res) {
					if (res.confirm) {
						beforeIsExistUser(type)
					}
				}
			})
		}
	}
	// 保存草稿箱前验证
	const beforeIsExistUser = type =>{
		if (Info.value.c_receiver == "" || Info.value.c_receiver == " " || Info.value.c_receiver == "*") {
			Info.value.c_receiver = '*';
			//验证抄送者是否正确
			if (Info.value.c_copy_receiver) {
				IsExistUser(Info.value.c_copy_receiver,(obj)=>{
					if (obj != " ") {
						Info.value.c_copy_receiver='';
						Info.value.c_copy_receiver_name='';
						uni.showToast({
							duration: 3500,
							icon: 'none',
							title: "抄送人没有找到" + obj + "的匹配用户，请重新输入!"
						});
					}else{
						if(type=='saveDraft'){
							SaveDraft();
						}else{
							SendMail();
						}
					}
				});
			} else {
				if(type=='saveDraft'){
					SaveDraft();
				}else{
					SendMail();
				}
			}
		}else{
			IsExistUser(Info.value.c_receiver,(obj)=>{
				if (obj != " ") {
					Info.value.c_receiver='';
					Info.value.c_receiver_name='';
					uni.showToast({
						duration: 3500,
						icon: 'none',
						title: "收件人没有找到" + obj + "的匹配用户，请重新输入!"
					});
				}else{
					//验证抄送者是否正确
					if (Info.value.c_copy_receiver) {
						IsExistUser(Info.value.c_copy_receiver,(obj)=>{
							if (obj != " ") {
								Info.value.c_copy_receiver='';
								Info.value.c_copy_receiver_name='';
								uni.showToast({
									duration: 3500,
									icon: 'none',
									title: "抄送人没有找到" + obj + "的匹配用户，请重新输入!"
								});
							}else{
								if(type=='saveDraft'){
									SaveDraft();
								}else{
									SendMail();
								}
							}
						});
					} else {
						if(type=='saveDraft'){
							SaveDraft();
						}else{
							SendMail();
						}
					}
				}
			});
		}
	}
	const IsExistUser = (e,func) =>{
		service.enjoyShowLoading('正在验证...');
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40内部邮件",
		        ObjectData: e,
		        MethodName: "IsExistUser",
		    },
		}
		service.request(request, (res) => {
			service.enjoyHideLoading();
		    if (res && res.data) {
		        if (!res.data.HasException) {
					const ObjectData = res.data.ObjectData;
					if(func){
						func(ObjectData)
					}
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
		}, () => {
			service.enjoyHideLoading();
		    console.log('失败')
		});
	}
	const SaveDraft = () =>{
		service.enjoyShowLoading('正在处理...');
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40内部邮件",
		        ObjectData: {
					c_sender: mainStore.loginInfo.sUser,
					c_title: Info.value.c_title,
					c_email_send_type: "4",
					c_receiver: Info.value.c_receiver,
					c_copy_receiver: Info.value.c_copy_receiver,
					c_content: Info.value.c_content,
					c_guid: idGuid.value,
					c_mk_dt: dateRangUtil.formatDate('','YYYY-MM-DD HH:mm:ss'),
					c_is_send_exterior: "否",
					c_is_send_sms: "否",
					c_is_attachment: Info.value.attachment.length>0?"是":"否",
					c_exterior_receiver: "",
					c_organ_receiver: "",
					c_depart_receiver: "",
					c_station_receiver: "",
					c_id: c_id.value
				},
		        MethodName: "SaveDraft",
		    },
		}
		service.request(request, (res) => {
			service.enjoyHideLoading();
		    if (res && res.data) {
		        if (!res.data.HasException) {
					const ObjectData = res.data.ObjectData;
					if (Info.value.attachment.length>0) {
						AddEmailAttachment(ObjectData,idGuid.value);
					}else{
						SetCurrentPages();
						uni.navigateBack();
						uni.showToast({
							duration: 3500,
							icon: 'none',
							title: "保存成功!"
						});
					}
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
		}, () => {
			service.enjoyHideLoading();
		    console.log('失败')
		});
	}
	// 发送前验证
	const SendMail = () =>{
		service.enjoyShowLoading('正在处理...');
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40内部邮件",
		        ObjectData: {
					c_sender: mainStore.loginInfo.sUser,
					c_title: Info.value.c_title,
					c_email_send_type: "1",
					c_receiver: Info.value.c_receiver,
					c_copy_receiver: Info.value.c_copy_receiver,
					c_content: Info.value.c_content,
					c_guid: idGuid.value,
					c_mk_dt: dateRangUtil.formatDate('','YYYY-MM-DD HH:mm:ss'),
					c_is_send_exterior: "否",
					c_is_send_sms: "否",
					c_is_attachment: Info.value.attachment.length>0?"是":"否",
					c_exterior_receiver: "",
					c_organ_receiver: "",
					c_depart_receiver: "",
					c_station_receiver: "",
					c_id: c_id.value
				},
		        MethodName: "sendMail",
		    },
		}
		service.request(request, (res) => {
			service.enjoyHideLoading();
		    if (res && res.data) {
		        if (!res.data.HasException) {
					const ObjectData = res.data.ObjectData;
					if (Info.value.attachment.length>0) {
						AddEmailAttachment(ObjectData,idGuid.value);
					}else{
						SetCurrentPages();
						uni.navigateBack();
						uni.showToast({
							duration: 3500,
							icon: 'none',
							title: "发送成功!"
						});
					}
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
		}, () => {
			service.enjoyHideLoading();
		    console.log('失败')
		});
	}
	// 图片上传
	const resultUrl = async (v, size) => {
		console.log("resultUrl: " + JSON.stringify(v)+ JSON.stringify(size));
		const req = {
			url: v.url,
			c_guid: '',
			c_imgGuid: v.c_guid,
			c_bill_id: '',
			c_bill_type: '邮件管理',
			c_name: v.file,
			c_file_name: v.file,
			c_file_size: size,
			c_file_ext: v.file.split('.')[v.file.split('.').length-1],
			c_modified_dt: dateRangUtil.formatDate('','YYYY-MM-DD HH:mm:ss'),
		};
		Info.value.attachment.push(req)
	}
	// 删除图片
	const delImg = (e) => {
		console.log(345, "delImg", e);
		if(e.c_imgGuid){
			const list = Info.value.attachment.filter(item=>item.c_imgGuid!=e.c_imgGuid);
			Info.value.attachment = list;
			if(e.c_guid){
				DeleteEmailAttachment(e.c_guid);
			}
			//在DeleteEmailAttachment中已经同步处理了删除MongoDB文件，这里不需要单独处理了 CT 20241015
			//DeleteMongodbDoc(e.c_guid);
		}
	}
	const DeleteEmailAttachment = guid =>{
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40内部邮件",
		        ObjectData: guid,
		        MethodName: "DeleteEmailAttachment",
		    },
		}
		service.request(request, (res) => {
		    if (res && res.data) {
		        if (!res.data.HasException) {
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
		}, () => {
		    console.log('失败')
		});
	}
	const DeleteMongodbDoc = guid =>{
		//在DeleteEmailAttachment中已经同步处理了删除MongoDB文件，这里不需要单独处理了
		/* let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40商品随手记",
		        ObjectData: guid,
		        MethodName: "DeleteMongodbDoc",
		    },
		}
		service.request(request, (res) => {
		    if (res && res.data) {
		        if (!res.data.HasException) {
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
		}, () => {
		    console.log('失败')
		}); */
	}
	const AddEmailAttachment = async (fileId,guid) =>{
		service.enjoyShowLoading('正在处理...');
		const lists = Info.value.attachment || [];
		const extendInfo = JSON.stringify({
			BillId: fileId,
			BillType: '邮件管理',
		});
		let list = [];
		for (let i = 0; i < lists.length; i++) {
			if(!lists[i].upload){
				const file = lists[i];
				const result = await upload({
					file: {
						ext: file.c_file_name,
						url: file.url,
						name: file.c_file_name,
						type: file.c_file_ext,
						guid: guid
					},
					uploadUserNo: mainStore.loginInfo.sUser,
					extendInfo: extendInfo,
				});
				console.log("result: " + JSON.stringify(result));
				Info.value.attachment[i].c_guid = result?.guid;
				Info.value.attachment[i].c_bill_id = guid + 'file';
				if(result&&result.guid){
					list.push(Info.value.attachment[i])
				}
			}
		}
		if(list.length>0){
			let request = {
			    url: LoginStore.EnjoyMain,
			    data: {
			        UniqueKey: "管易通40内部邮件",
			        ObjectData: list,
			        MethodName: "AddEmailAttachment",
			    },
			}
			service.request(request, (res) => {
				service.enjoyHideLoading();
			    if (res && res.data) {
			        if (!res.data.HasException) {
						const ObjectData = res.data.ObjectData;
						SetCurrentPages();
						uni.navigateBack();
						uni.showToast({
							duration: 3500,
							icon: 'none',
							title: "保存成功!"
						});
			        } else {
			            service.enjoyShowToast(res.data.Exception.Message)
			        }
			    }
			}, () => {
			    console.log('失败')
				service.enjoyHideLoading();
			});
		}else{
			SetCurrentPages();
			uni.navigateBack();
			uni.showToast({
				duration: 3500,
				icon: 'none',
				title: "保存成功!"
			});
		}
	}
	const EnjoyBillQuery = BillId =>{
		service.enjoyShowLoading('正在加载...');
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40内部邮件",
		        ObjectData: {
					BillId
				},
		        MethodName: "EnjoyBillQuery",
		    },
		}
		service.request(request, (res) => {
		    if (res && res.data) {
		        if (!res.data.HasException) {
					const ObjectData = res.data.ObjectData;
					if(ObjectData != null && ObjectData.ds.length > 0) {
						Info.value = {
							...ObjectData.ds[0],
							c_receiver_name:ObjectData.ds[0].c_receiver_name,
							c_copy_receiver_name:ObjectData.ds[0].c_copy_receiver_name,
							attachment:[],
						};
						idGuid.value = ObjectData.ds[0].c_guid;
						DocGetContent(ObjectData.ds[0].c_guid);
						GetAccessDoc(ObjectData.ds[0].c_guid);
					}
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
			service.enjoyHideLoading();
		}, () => {
			service.enjoyHideLoading();
		    console.log('失败')
		});
	}
	// 获取内容
	const DocGetContent = c_guid =>{
		service.enjoyShowLoading('正在加载...');
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40公共",
		        ObjectData: c_guid,
		        MethodName: "DocGetContent",
		    },
		}
		service.request(request, (res) => {
		    if (res && res.data) {
		        if (!res.data.HasException) {
					const ObjectData = res.data.ObjectData;
					const reg = /<(.*)>.*<\/\1>|<(.*) \/>/;
					//区分是否是后台数据（含html)
					if (!reg.test(unescape(ObjectData))) {
						readOnly.value = false;
						Info.value.c_content = unescape(ObjectData);
					}
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
			service.enjoyHideLoading();
		}, () => {
			service.enjoyHideLoading();
		    console.log('失败')
		});
	}
	// 获取附件
	const GetAccessDoc = c_guid =>{
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40内部邮件",
		        ObjectData: {
					sBillId:c_guid+'file',
					sBillType: '邮件管理'
				},
		        MethodName: "GetAccessDoc",
		    },
		}
		service.request(request, (res) => {
		    if (res && res.data) {
		        if (!res.data.HasException) {
					const ObjectData = res.data.ObjectData;
					let list = [];
					let type2 = '';
					const Url = LoginStore.EnjoyMain.replace('/Enjoy/Service', '');
					for (let i = 0; i < ObjectData.length; i++) {
						type2 = ObjectData[i].c_file_name.substring(ObjectData[i].c_file_name.lastIndexOf('.') + 1, ObjectData[i].c_file_name.length);
						type2 = type2.toLowerCase();
						list.push({
							...ObjectData[i],
							url: Url + '/File/DownLoadFile/' + ObjectData[i].c_guid,
							id:ObjectData[i].c_guid,
							upload:true,
							result: null,
							c_type:['jpeg','jpg','png'].includes(type2) ? type2 : 'file',
							file:ObjectData[i].c_file_name,
							c_imgGuid:ObjectData[i].c_guid,
						})
					}
					fileList.value = JSON.parse(JSON.stringify(list));
					Info.value.attachment = JSON.parse(JSON.stringify(list));
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
		}, () => {
		    console.log('失败')
		});
	}
	const SetCurrentPages = () =>{
		try {
			let pages = getCurrentPages();
			let prevPage = pages[pages.length - 2];
			prevPage.$vm.$.exposed.onRefresh();
		} catch (e) {
		}
	}
	onLoad((e)=>{
		console.log("e: " + JSON.stringify(e));
		readOnly.value = false;
		if(e.to){
			Info.value.c_receiver=e.to;
			Info.value.c_receiver_name=e.tousername?e.tousername:'';
		}
		if(e.title){
			Info.value.c_title = e.title;
		}
		if(e.item){
			const list = JSON.parse(e.item);
			c_id.value = list.c_id;
			EnjoyBillQuery(list.c_id);
		}else{
			idGuid.value = Guid.NewGuid().ToString();
		}
	})
	defineExpose({
		resultUrl,
		delImg
	})
</script>

<style lang="scss" scoped>
	@import '@/main.scss';

	.content-img {
		background-color: #FFFFFF;
		background-repeat: no-repeat;
		width: 100%;
	}

	.main-view {
		flex: 1;
		flex-direction: column;
		background-color: #f2f2f2;
	}

	.padding-left-20 {
		padding-left: 20rpx !important;
	}

	.padding-left-28 {
		padding-left: 28rpx !important;
	}

	.margin-top-28 {
		margin-top: 28rpx;
	}

	.font-size-28 {
		font-size: 28rpx;
	}

	.color-666 {
		color: #666;
	}

	.user-footer {
		position: fixed;
		z-index: 9;
		bottom: 0;
		left: 0rpx;
		right: 0rpx;
		padding-left: 13rpx;
		padding-right: 13rpx;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	::v-deep .uni-textarea-placeholder {
		color: rgba(204, 204, 204, 1);
	}
	::v-deep .m-button-base{
		width: 100%;
		    margin: 15rpx;
	}
</style>